package com.yaodian100.ec.product.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.yaodian100.core.admin.utils.AdminHelper;
import com.yaodian100.core.common.dao.ObjectDao;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.service.impl.DomainServiceImpl;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.logger.service.LogService;
import com.yaodian100.core.mail.entity.Mail;
import com.yaodian100.core.mail.service.MailService;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.crm.cs.service.CsService;
import com.yaodian100.crm.workorder.service.WorkOrderService;
import com.yaodian100.ec.campaign.entity.Campaign;
import com.yaodian100.ec.campaign.service.CampaignService;
import com.yaodian100.ec.common.EnvParameters;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.order.entity.OrderProductDetail;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.service.OrderService;
import com.yaodian100.ec.product.entity.OrderComment;
import com.yaodian100.ec.product.entity.OrderCommentLog;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.ProductComment;
import com.yaodian100.ec.product.entity.OrderComment.COMMENT_STATUS;
import com.yaodian100.ec.product.service.OrderCommentService;

public class OrderCommentServiceImpl extends DomainServiceImpl<OrderComment> implements OrderCommentService {

	@Autowired
	private BaseManager baseMgr;
	@Autowired
	private OrderService orderService;
	@Autowired
	private MemberService memberService;
	@Resource
	private TemplateService velocityService;
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private MailService mailService;
	@Resource
	private EnvParameters envParameters;
	@Resource
	private LogService logService;
	@Resource
	private WorkOrderService workOrderService;
	@Resource
	private CampaignService campaignService;
	@Autowired
	private CsService csService;

	private ObjectDao<OrderCommentLog> orderCommentLogDao;
	private ObjectDao<ProductComment> productCommentDao;
	/** pageRecord, 每頁筆数 */
	private final int pageRecord = 10;
	/** totalSize, 全部筆數 */
	private final int unitPage = 10; // 每十頁為一個單位

	@Override
	@Transactional(readOnly = false)
	public OrderComment saveOrderComment(OrderComment oc) {
		// 檢查是否有重覆評論
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("orderDetailId", oc.getOrderDetailId());
		if (this.getListSize(crit).intValue() > 0) {
			throw new CoreException("already.comment");
		}
		// 檢查訂單狀態
		Orders order = orderService.get(oc.getOrderId());
		if ("35,90".indexOf(order.getOrderSt()) == -1) {
			throw new CoreException("orderSt.notCorrect");
		}
		if (!order.getMemberId().equals(oc.getMemberId())) {
			throw new CoreException("member.notCorrect");
		}
		// 檢查訂單是否超過期限，不允許評價
		OrderProductDetail opd = orderService.getOrderProductDetail(oc.getOrderDetailId());
		if (opd == null) {
			throw new CoreException("orderDetail.notCorrect");
		}
		oc.setLoginId(order.getLoginId());
		oc.setReceiverProvince(order.getReceiverProvince());
		oc.setSpecName(opd.getProdSpecName());
		oc.setProductName(opd.getProdName());
		oc.setProductId(opd.getProdId());
		oc.setCommentStatus(OrderComment.COMMENT_STATUS.NEW.getValue());
		this.save(oc);
		return oc;
	}

	/*
	 * (non-Javadoc) 將評價轉為工單
	 * 
	 * @see com.yaodian100.ec.product.service.OrderCommentService#commentToWorkorder(int)
	 */
	@Override
	@Transactional(readOnly = false)
	public boolean commentToWorkorder(int size) {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("commentStatus", COMMENT_STATUS.NEW);
		crit.addEq("createDate", COMMENT_STATUS.NEW);
		Object[] commentList = baseMgr.queryByHql(
				"from OrderComment where createDate < (sysdate-1/24/60*20) and commentStatus ='00' and rownum <" + size,
				new Object[] {});
		for (Object obj : commentList) {
			OrderComment oc = (OrderComment) obj;
			csService.createCheckProductComment(oc.getCmid(), oc.getMemberId(), oc.getProductName(), oc.getSubject(), oc
					.getContent(), oc.getProductId());
			oc.setCommentStatus(COMMENT_STATUS.PROCESS.getValue());
			this.update(oc);
		}
		return true;
	}

	@Override
	@Transactional(readOnly = false)
	public OrderComment rePostOrderComment(OrderComment oc) {
		if (oc == null) {
			throw new CoreException("orderComment.notCorrect");
		}
		if (oc.getCommentStatus().equals(OrderComment.COMMENT_STATUS.APPROVE.getValue())) {
			throw new CoreException("orderComment.notRepost");
		}
		if (oc.getCommentStatus().equals(OrderComment.COMMENT_STATUS.FAIL.getValue())
				|| oc.getCommentStatus().equals(OrderComment.COMMENT_STATUS.NEW.getValue())) {
			oc.setCommentStatus(OrderComment.COMMENT_STATUS.NEW.getValue());
			this.update(oc);
			return oc;
		} else {
			throw new CoreException("commentStatus.notCorrect");
		}
	}

	@Override
	@Transactional(readOnly = false)
	public OrderComment approveOrderCommentByWorkorder(String cmid, String commentStatus, String failReason)
			throws NumberFormatException, Exception {
		return approveOrderComment(cmid, commentStatus, failReason, "workorder");
	}

	@Override
	@Transactional(readOnly = false)
	public OrderComment approveOrderComment(String cmid, String commentStatus, String failReason, String from)
			throws NumberFormatException, Exception {
		OrderComment entity = this.get(cmid);
		String velocityTemplate = "";
		String mailSubject = "";
		if (entity == null) {
			throw new CoreException("orderComment.notCorrect");
		}
		if (OrderComment.COMMENT_STATUS.valueOf(commentStatus) == null) {
			throw new CoreException("commentStatus.notCorrect");
		}
		if (commentStatus.equals(OrderComment.COMMENT_STATUS.APPROVE.name())) {
			Campaign campaign = campaignService.getActiveBonusCampaignByM04(null);
			if (getLast3CommentByProductId(entity.getProductId()).size() < 4) {
				entity.setBonus(new BigDecimal(campaign.getCommentFirst3()));
			} else {
				entity.setBonus(new BigDecimal(campaign.getCommentOthers()));
			}
			if (entity.getBonus().intValue() > 0) {
				memberService.giveBonus(entity.getMemberId(), entity.getBonus(), "商品评价赠送积分", "EVENT_POINT", DateUtils.addDays(
						new Date(), Integer.parseInt(campaign.getStartPeriod())), DateUtils.addDays(new Date(), Integer
						.parseInt(campaign.getPeriodDays())));
			}
			velocityTemplate = "comment.approved";
			mailSubject = "商品评价审核通知";
		}
		if (commentStatus.equals(OrderComment.COMMENT_STATUS.FAIL.name())) {
			entity.setFailCount(entity.getFailCount() + 1);
			entity.setFailReason(failReason);
			velocityTemplate = "comment.not.approved";
			mailSubject = "商品评价审核通知";
		}
		// 記錄訊息LOG
		if (StringUtils.isNotBlank(failReason)) {
			addCommentLog(cmid, OrderComment.COMMENT_STATUS.valueOf(commentStatus).getValue(), failReason);
		}
		entity.setApproveDate(DateUtil.getCurrentTime());
		entity.setApproveMan(AdminHelper.getUser().getUsername());
		entity.setCommentStatus(OrderComment.COMMENT_STATUS.valueOf(commentStatus).getValue());
		this.save(entity);
		if (commentStatus.equals(OrderComment.COMMENT_STATUS.APPROVE.name())) {
			calcProductComment(entity.getProductId());
		}
		try {
			Map<String, Object> contentMap = new HashMap<String, Object>();
			contentMap.put("comment", entity);
			contentMap.put("contextpath", ServerValue.getFrontContextPath());
			contentMap.put("basehref", ServerValue.getFrontHostname());
			Mail mail = velocityService.formatToMail(velocityTemplate, contentMap);
			mail.setFrom(envParameters.getEmailFromSystem());
			mail.setSubject(mailSubject);
			mail.setTo(memberService.get(entity.getMemberId()).getSendEmail());
			mailService.save(mail);
		} catch (Exception e) {
			logService.save(this.getClass().getName(), "approveOrderComment.sendmail", entity);
		}
		if (!"workorder".equals(from)) {
			workOrderService.closeProductCommentOrderFromCM(cmid, failReason);
		}
		return entity;
	}

	@Override
	@Transactional(readOnly = false)
	public boolean addCommentLog(String cmid, String type, String failReason) {
		OrderCommentLog ocl = new OrderCommentLog();
		ocl.setCmid(cmid);
		ocl.setType(type);
		ocl.setFailReason(failReason + " - " + AdminHelper.getUser().getUsername() + " @ "
				+ DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", DateUtil.getCurrentTime()));
		orderCommentLogDao.save(ocl);
		return true;
	}

	@Override
	@Transactional(readOnly = false)
	public boolean hideOrderComment(String cmid, String hide) {
		OrderComment entity = this.get(cmid);
		if ("YN".indexOf(hide) == -1) {
			throw new CoreException("hidetype.notCorrect");
		}
		entity.setHideYn(hide);
		this.save(entity);
		calcProductComment(entity.getProductId());
		return true;
	}

	@Override
	@Transactional(readOnly = false)
	public boolean calcProductComment(String productId) {
		Product prod = (Product) baseMgr.get(Product.class, productId);
		if (prod == null) {
			throw new CoreException("product.notfound");
		}
		Object[] mainDataList = baseMgr.queryByHql("select count(*), nvl(round(avg(score),1),0) from OrderComment "
				+ "where productId = '" + productId + "' and hideYn = 'N' and commentStatus = '90' ", new Object[] {});

		List<Map<String, Object>> commentDataList = jdbcTemplate
				.queryForList("select decode(score,5,'Good',4,'Good',3,'Mid',2,'Mid',1,'Low') as score_type ,count(score) as score from ec_order_comment "
						+ "where hide_yn = 'N' and comment_status = '90' and product_id = '"
						+ productId
						+ "' group by decode(score,5,'Good',4,'Good',3,'Mid',2,'Mid',1,'Low') ");

		Object[] sizeDataList = baseMgr.queryByHql("select size,count(size) from OrderComment " + "where productId = '"
				+ productId + "' and size_data in ( 'B','C','D')  and hideYn = 'N' and commentStatus = '90' group by size ",
				new Object[] {});

		if (mainDataList != null) {
			ProductComment entity = productCommentDao.get(productId);
			if (entity == null) {
				entity = new ProductComment();
				entity.setProductId(productId);
			}

			Object[] mainData = (Object[]) mainDataList[0];
			entity.setTotalRecord(new Integer(mainData[0].toString()));
			entity.setAvgScore((new BigDecimal(mainData[1].toString())).setScale(1));
			BigDecimal goodScore = new BigDecimal("0");
			BigDecimal midScore = new BigDecimal("0");
			BigDecimal lowScore = new BigDecimal("0");

			BigDecimal bigSize = new BigDecimal("0");
			BigDecimal midSize = new BigDecimal("0");
			BigDecimal smallSize = new BigDecimal("0");
			entity.setGoodRecord(0);
			entity.setMidRecord(0);
			entity.setLowRecord(0);

			entity.setGoodScore(goodScore);
			entity.setMidScore(goodScore);
			entity.setLowScore(goodScore);

			entity.setBigSize(goodScore);
			entity.setMidSize(goodScore);
			entity.setSmallSize(goodScore);
			// 抓取好評壞評統計
			if (commentDataList != null) {
				for (Map<String, Object> commentData : commentDataList) {
					if ("Good".equals(commentData.get("SCORE_TYPE"))) {
						goodScore = new BigDecimal(commentData.get("SCORE").toString());
						entity.setGoodRecord(goodScore.intValue());
					} else if ("Mid".equals(commentData.get("SCORE_TYPE"))) {
						midScore = new BigDecimal(commentData.get("SCORE").toString());
						entity.setMidRecord(midScore.intValue());
					} else if ("Low".equals(commentData.get("SCORE_TYPE"))) {
						lowScore = new BigDecimal(commentData.get("SCORE").toString());
						entity.setLowRecord(lowScore.intValue());
					}
				}
			}

			// 抓取尺寸壞評統計
			if (sizeDataList != null) {
				for (Object obj : sizeDataList) {
					Object[] sizeData = (Object[]) obj;
					if ("B".equals(sizeData[0].toString())) {
						bigSize = new BigDecimal(sizeData[1].toString());
					}
					if ("C".equals(sizeData[0].toString())) {
						midSize = new BigDecimal(sizeData[1].toString());
					}
					if ("D".equals(sizeData[0].toString())) {
						smallSize = new BigDecimal(sizeData[1].toString());
					}
				}
			}
			// (好評加總/(好評加總+中評加總+差評加總))*100,其他依此類推
			if ((goodScore.add(midScore).add(lowScore)).compareTo(new BigDecimal("0")) != 0) {
				entity.setGoodScore((goodScore.divide(goodScore.add(midScore).add(lowScore), 2, RoundingMode.HALF_UP)
						.multiply(new BigDecimal("100"))).setScale(0));
				entity.setMidScore((midScore.divide(goodScore.add(midScore).add(lowScore), 2, RoundingMode.HALF_UP)
						.multiply(new BigDecimal("100"))).setScale(0));
				entity.setLowScore((lowScore.divide(goodScore.add(midScore).add(lowScore), 2, RoundingMode.HALF_UP)
						.multiply(new BigDecimal("100"))).setScale(0));
			}
			// (大尺碼加總/(大尺碼加總+中尺碼加總+小尺碼加總))*100,其他依此類推
			if ((bigSize.add(midSize).add(smallSize)).compareTo(new BigDecimal("0")) != 0) {
				entity.setBigSize((bigSize.divide(bigSize.add(midSize).add(smallSize), 2, RoundingMode.HALF_UP)
						.multiply(new BigDecimal("100"))).setScale(0));
				entity.setMidSize((midSize.divide(bigSize.add(midSize).add(smallSize), 2, RoundingMode.HALF_UP)
						.multiply(new BigDecimal("100"))).setScale(0));
				entity.setSmallSize((smallSize.divide(bigSize.add(midSize).add(smallSize), 2, RoundingMode.HALF_UP)
						.multiply(new BigDecimal("100"))).setScale(0));
			}
			productCommentDao.saveOrUpdate(entity);
		}
		return true;
	}

	@Override
	public List<OrderComment> getLast3CommentByProductId(String productId) {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("productId", productId);
		crit.addEq("commentStatus", OrderComment.COMMENT_STATUS.APPROVE.getValue());
		crit.addEq("hideYn", "N");
		return this.getList(0, 10, crit, new String[] { "approveDate asc" });
	}

	@Override
	public ProductComment getProductCommentByProductId(String productId) {
		if (StringUtils.isBlank(productId)) {
			throw new CoreException("product.notCorrect");
		}
		return productCommentDao.get(productId);
	}

	@Override
	public List<OrderCommentLog> getOrderCommnetLogByCmid(String cmid) {
		if (StringUtils.isBlank(cmid)) {
			throw new CoreException("orderComment.notCorrect");
		}
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("cmid", cmid);
		return orderCommentLogDao.getListPageable(crit, new String[] { "modifyDate desc" }, 0, 5);
	}

	// 可评价的商品
	@Override
	public List<Object> getOrderCommentListByMemberId(String memberId, String orderId, String detailProdId,
			int firstResult, int maxResult) {
		List<Object> paramsList = new ArrayList<Object>();
		StringBuffer sbSql = new StringBuffer();
		sbSql
				.append("select distinct od.prodId,od.prodName,od.prodSpecName,om.orderId,om.orderDt,od.orderDetailId,op.prodId ");
		sbSql.append("from Orders om,OrderProduct op,OrderProductDetail od ");
		sbSql.append("where	om.orderId = op.orderId and op.orderId = od.orderId ");
		sbSql.append("and op.orderProdId = od.orderProdId and om.orderSt in ('35','90') ");
		sbSql.append("and od.prodId not in ( select oc.productId from OrderComment oc ");
		sbSql.append("where om.memberId = oc.memberId and od.prodId = oc.productId ) ");
		sbSql.append("and om.orderDt >= (sysdate-180) and om.memberId = ? ");
		paramsList.add(memberId);
		if (StringUtils.isNotEmpty(detailProdId)) {
			String[] detailProdIds = detailProdId.split(",");
			sbSql.append("and od.orderDetailId in ( ");
			int i = 0;
			for (String tmpDetailProdId : detailProdIds) {
				sbSql.append(" ? ");
				if (i < detailProdIds.length - 1) {
					sbSql.append(",");
				}
				paramsList.add(tmpDetailProdId);
				i++;
			}
			sbSql.append(" ) ");
		}
		if (StringUtils.isNotEmpty(orderId)) {
			String[] orderIds = orderId.split(",");
			sbSql.append("and om.orderId in ( ");
			int i = 0;
			for (String tmpOrderId : orderIds) {
				sbSql.append(" ? ");
				if (i < orderIds.length - 1) {
					sbSql.append(",");
				}
				paramsList.add(tmpOrderId);
				i++;
			}
			sbSql.append(" ) ");
		}
		sbSql.append("order by om.orderDt desc ");
		Object[] objs = baseMgr.queryByHql(sbSql.toString(), paramsList.toArray(new Object[0]), firstResult, maxResult);
		List<Object> objList = Arrays.asList(objs);
		return objList;
	}

	@Override
	public Number getOrderCommentListByMemberId(String memberId, String orderId, String detailProdId) {
		return getOrderCommentListByMemberId(memberId, orderId, detailProdId, "");
	}

	@Override
	public Number getOrderCommentListByMemberId(String memberId, String productId) {
		return getOrderCommentListByMemberId(memberId, "", "", productId);
	}

	// 可评价的商品數
	Number getOrderCommentListByMemberId(String memberId, String orderId, String detailProdId, String productId) {
		List<Object> paramsList = new ArrayList<Object>();
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("select count(*) from Orders om,OrderProductDetail od ");
		sbSql.append("where	om.orderId = od.orderId and om.orderSt in ('35','90') ");
		sbSql.append("and od.prodId not in ( select oc.productId from OrderComment oc ");
		sbSql.append("where om.memberId = oc.memberId and od.prodId = oc.productId ) ");
		sbSql.append("and om.orderDt >= (sysdate-180) and om.memberId = ? ");
		paramsList.add(memberId);
		if (StringUtils.isNotEmpty(productId)) {
			sbSql.append("and od.prodId = ? ");
			paramsList.add(productId);
		}
		if (StringUtils.isNotEmpty(detailProdId)) {
			String[] detailProdIds = detailProdId.split(",");
			sbSql.append("and od.orderDetailId in ( ");
			int i = 0;
			for (String tmpDetailProdId : detailProdIds) {
				sbSql.append(" ? ");
				if (i < detailProdIds.length - 1) {
					sbSql.append(",");
				}
				paramsList.add(tmpDetailProdId);
				i++;
			}
			sbSql.append(" ) ");
		}
		if (StringUtils.isNotEmpty(orderId)) {
			String[] orderIds = orderId.split(",");
			sbSql.append("and om.orderId in ( ");
			int i = 0;
			for (String tmpOrderId : orderIds) {
				sbSql.append(" ? ");
				if (i < orderIds.length - 1) {
					sbSql.append(",");
				}
				paramsList.add(tmpOrderId);
				i++;
			}
			sbSql.append(" ) ");
		}
		Long commentNumber = baseMgr.countByHql(sbSql.toString(), paramsList.toArray(new Object[0]));
		if (commentNumber > 0) {
			return NumberUtils.createNumber(String.valueOf(commentNumber));
		} else {
			return 0;
		}

	}

	@Override
	public Map<String, Object> getOrderComments(String memberId, String orderId, String productId, int page)
			throws CoreException {
		Map<String, Object> infoMap = new HashMap<String, Object>();
		try {
			int totalSize = getOrderCommentListByMemberId(memberId, orderId, productId).intValue();
			SimplePager pager = new SimplePager();
			pager.setPageRecord(pageRecord);
			pager.setTotalSize(totalSize);

			infoMap.put("totalPage", pager.getPageSize());
			infoMap.put("totalCount", totalSize);
			infoMap.put("pageRecord", pageRecord);
			infoMap.put("frontContextPath", ServerValue.getFrontContextPath());

			pager.setCurrentPage(page);

			List<Object> orderCommentList = getOrderCommentListByMemberId(memberId, orderId, productId, pager
					.getCurrentPage()
					* pager.getPageRecord(), pager.getPageRecord());

			infoMap.put("orderCommentList", orderCommentList);

			infoMap.put("currentPage", pager.getCurrentPage() + 1);
			infoMap.put("totalCount_T", totalSize);
			int k = page / unitPage;
			int startPage = k * unitPage + 1;
			int endPage = (k + 1) * unitPage;
			if (endPage > pager.getPageSize()) {
				endPage = pager.getPageSize();
			}

			infoMap.put("startPage", startPage);
			infoMap.put("endPage", endPage);

		} catch (Exception e) {
			e.printStackTrace();
			throw new CoreException("產生錯誤");
		}
		return infoMap;
	}

	@Override
	public Map<String, Object> getOrderCommentHistory(String memberId, int page, String commentStParam)
			throws CoreException {
		Map<String, Object> infoMap = new HashMap<String, Object>();
		try {

			// 可评价的商品數
			int commentListSize = getOrderCommentListByMemberId(memberId, "", "").intValue();
			infoMap.put("commentListSize", commentListSize);

			// 已发表的评价
			CommonCriteria crit = new CommonCriteria();
			crit.addEq("memberId", memberId);
			if (StringUtils.isNotEmpty(commentStParam)) {
				crit.addEq("commentStatus", commentStParam);
			}
			int totalSize = getList(0, -1, crit, new String[] { "createDate desc" }).size();
			SimplePager pager = new SimplePager();
			pager.setPageRecord(pageRecord);
			pager.setTotalSize(totalSize);

			infoMap.put("totalPage", pager.getPageSize());
			infoMap.put("totalCount", totalSize);
			infoMap.put("pageRecord", pageRecord);
			infoMap.put("frontContextPath", ServerValue.getFrontContextPath());

			pager.setCurrentPage(page);
			crit = new CommonCriteria();
			crit.addEq("memberId", memberId);
			if (StringUtils.isNotEmpty(commentStParam)) {
				crit.addEq("commentStatus", commentStParam);
			}
			List<OrderComment> commentHistoryList = this.getList(pager.getCurrentPage() * pager.getPageRecord(), pager
					.getPageRecord(), crit, new String[] { "createDate desc" });
			infoMap.put("commentHistoryList", commentHistoryList);

			infoMap.put("currentPage", pager.getCurrentPage() + 1);
			infoMap.put("totalCount_T", totalSize);
			int k = page / unitPage;
			int startPage = k * unitPage + 1;
			int endPage = (k + 1) * unitPage;
			if (endPage > pager.getPageSize()) {
				endPage = pager.getPageSize();
			}

			infoMap.put("startPage", startPage);
			infoMap.put("endPage", endPage);

		} catch (Exception e) {
			e.printStackTrace();
			throw new CoreException("產生錯誤");
		}
		return infoMap;
	}

	public BaseManager getBaseMgr() {
		return baseMgr;
	}

	public void setBaseMgr(BaseManager baseMgr) {
		this.baseMgr = baseMgr;
	}

	public OrderService getOrderService() {
		return orderService;
	}

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	public ObjectDao<OrderCommentLog> getOrderCommentLogDao() {
		return orderCommentLogDao;
	}

	public void setOrderCommentLogDao(ObjectDao<OrderCommentLog> orderCommentLogDao) {
		this.orderCommentLogDao = orderCommentLogDao;
	}

	public ObjectDao<ProductComment> getProductCommentDao() {
		return productCommentDao;
	}

	public void setProductCommentDao(ObjectDao<ProductComment> productCommentDao) {
		this.productCommentDao = productCommentDao;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public TemplateService getVelocityService() {
		return velocityService;
	}

	public void setVelocityService(TemplateService velocityService) {
		this.velocityService = velocityService;
	}

	public MailService getMailService() {
		return mailService;
	}

	public void setMailService(MailService mailService) {
		this.mailService = mailService;
	}

	public EnvParameters getEnvParameters() {
		return envParameters;
	}

	public void setEnvParameters(EnvParameters envParameters) {
		this.envParameters = envParameters;
	}

	public LogService getLogService() {
		return logService;
	}

	public void setLogService(LogService logService) {
		this.logService = logService;
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public WorkOrderService getWorkOrderService() {
		return workOrderService;
	}

	public void setWorkOrderService(WorkOrderService workOrderService) {
		this.workOrderService = workOrderService;
	}

	public CampaignService getCampaignService() {
		return campaignService;
	}

	public void setCampaignService(CampaignService campaignService) {
		this.campaignService = campaignService;
	}

	public CsService getCsService() {
		return csService;
	}

	public void setCsService(CsService csService) {
		this.csService = csService;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.product.service.OrderCommentService#canComment(java.lang.String)
	 */
	@Override
	public boolean canComment(String memberId, String detailProdId, String func) {
		String[] detailProdIds = detailProdId.split(",");
		List<String> params = new ArrayList<String>();
		StringBuffer sb = new StringBuffer();
		sb.append("select * from OrderComment ");
		sb.append("where memberId = ? ");
		params.add(memberId);
		sb.append("and orderDetailId in ( ");
		int i = 0;
		for (String tmpDetailProdId : detailProdIds) {
			sb.append(" ? ");
			if (i < detailProdIds.length - 1) {
				sb.append(",");
			}
			i++;
			params.add(tmpDetailProdId);
		}
		sb.append(" ) ");
		if ("upd".equalsIgnoreCase(func)) {
			sb.append("and commentStatus in ( '00','80') ");
			sb.append("and failCount <= 1 ");
		}
		Long resultSize = baseMgr.countByHql(sb.toString(), params.toArray(new String[0]));
		if ("new".equalsIgnoreCase(func) && resultSize == 0) {
			return true;
		}
		if ("upd".equalsIgnoreCase(func)) {
			if (resultSize != detailProdIds.length) {
				return false;
			} else {
				return true;
			}
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.product.service.OrderCommentService#getProductCommentSize(java.lang.String)
	 */
	@Override
	public Map<String, String> getProductInfo(String detailProdId) {
		List<String> params = new ArrayList<String>();
		String[] detailProdIds = detailProdId.split(",");
		StringBuffer sb = new StringBuffer();
		sb
				.append("select distinct p.productId,p.commentSize from Product p,OrderProductDetail d where p.productId = d.prodId and d.orderDetailId in ( ");
		int i = 0;
		for (String tmpDetailProdId : detailProdIds) {
			sb.append(" ? ");
			if (i < detailProdIds.length - 1) {
				sb.append(",");
			}
			i++;
			params.add(tmpDetailProdId);
		}
		sb.append(" ) ");
		Object[] objList = baseMgr.queryByHql(sb.toString(), params.toArray(new String[0]));
		Map<String, String> prodInfoMap = new HashMap<String, String>();
		if (null != objList && objList.length > 0) {
			for (Object obj : objList) {
				Object[] objArray = (Object[]) obj;
				prodInfoMap.put(objArray[0].toString(), objArray[1].toString());
			}
		}
		return prodInfoMap;
	}
}